// 该页面为时间轴编辑页面，已归类到 timeline 目录
<script setup lang="ts">
  import { ref, watch, reactive } from 'vue'
  import { ElMessage } from 'element-plus'
  import { saveOrUpdate } from '@/api/timeline.ts'
  import { Timeline, TimelineSaveOrUpdateParam } from '@/types'

  interface Props {
    data?: Timeline
  }

  const props = defineProps<Props>()
  const emit = defineEmits(['close'])

  const formRef = ref()
  const formData = reactive<TimelineSaveOrUpdateParam>({
    id: undefined,
    title: '',
    content: '',
    date: '', // 添加 date 属性并初始化
  })

  const rules = {
    title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
    content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
    date: [{ required: true, message: '请选择日期', trigger: 'change' }], // 添加日期验证规则
  }

  watch(
    () => props.data,
    newData => {
      if (newData && newData.id) {
        formData.id = newData.id
        formData.title = newData.title
        formData.content = newData.content
        formData.date = newData.date // 填充日期
      } else {
        formData.id = undefined
        formData.title = ''
        formData.content = ''
        formData.date = '' // 新增时清空/初始化日期
      }
    },
    { immediate: true }
  )

  const handleSubmit = async () => {
    if (!formRef.value) return
    try {
      await formRef.value.validate()
      await saveOrUpdate(formData)
      ElMessage.success(formData.id ? '修改成功' : '新增成功')
      emit('close', true) // true indicates refresh parent list
    } catch (error) {
      console.error('保存失败:', error)
      ElMessage.error('操作失败')
    }
  }

  const handleCancel = () => {
    emit('close', false)
  }
</script>

<template>
  <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
    <el-form-item label="标题" prop="title">
      <el-input v-model="formData.title" placeholder="请输入标题" />
    </el-form-item>
    <el-form-item label="内容" prop="content">
      <el-input v-model="formData.content" type="textarea" rows="4" placeholder="请输入内容" />
    </el-form-item>
    <el-form-item label="日期" prop="date">
      <el-date-picker
        v-model="formData.date"
        type="date"
        placeholder="选择日期"
        value-format="YYYY-MM-DD"
        style="width: 100%"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handleSubmit">保存</el-button>
      <el-button @click="handleCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<style scoped></style>
